///////////*快递单打印controller*////////////
var OldSearch = null;
Ext.define('HIT.controller.ExpressPrint', {
    extend: 'Ext.app.Controller',
    models: ['ExpressPrint','CustomerContact'],
    stores: ['ExpressPrint','CustomerContact'],
    views: ['ExpressPrintGrid','ExpressPanel','ExpressSearchWin','ExpressComplexSearchWin','ExpressComplexSearchPanel'],
    onButtonClick: function(button, e, options) {
    	
    	function expressprint(printway,express,ids,expressStartNo,combine,printNum) {
    		Share.AjaxRequest({
                url: ctx + "/printExpress",
                params: {
                	printway : printway,
                	express: express,
                    ids: ids,
                    expressStartNo: expressStartNo,
                    combine: combine,
                    printNum: printNum
                },
                showMsg: false,
                scope: this,
                callback: function (json) {
                	//判断是否成功
                	if(json.resultcode == 0){
                		Share.ShowMessage("I0006","打印");
                		if (printway == 0) {
                			rootNode = Share.getLeftTree('left-report');
                			tabId = 'report-task';
                        	Ext.getStore('LeftTree').setRootNode(rootNode);                    	                                 
                        	var treepanel = Ext.getCmp('leftpanel');
                        	var record = treepanel.getRootNode().findChild("id", tabId, true);
                        	treepanel.getSelectionModel().select(record, true, false); 
                		}
                	}
                	else{
                		Share.ShowMessage("I0007","打印");
                	}
                	//刷新数据
					var tabpanelId = 'tab-deal-express';
					var tab = Ext.getCmp(tabpanelId);
					var store = tab.getStore();
					store.currentPage = 1;
					store.removeAll();
					store.on('beforeload', function(store) {
						Ext.apply(store.proxy.extraParams, {
							express : express
						});
					});
					store.load();
                }
            });
    	}if(button.id == 'deal-express-search'){
    		var s_win = Ext.create('widget.expresssearchwin');
        	Share.showWindow(s_win,true);
    	}if(button.id == 'express-search-complex'){
    		if(OldSearch == null){
    	  		var c_win = Ext.create('widget.expresscomplexsearchwin');
    	  		OldSearch = c_win;		
    	  		c_win.onEsc = function(){
    	  			return;
//    	  			this.hide();
    	  		};
    	  		Share.showWindow(c_win,true);
    	  	}else{
    	  		try{
    	  			OldSearch.show();
    	  		}catch(e){
    	  			var c_win = Ext.create('widget.dealcomplexsearchwin');
    	  			Share.showWindow(c_win,true);
    	  		}
    	  	}	
    	}if (button.id == 'experss-complex-search-save') {//执行高级查询  
        	//执行新的高级查询：
//        	var SearchDetailArray = new Array();  //存放查询数据的二维数组
//        	var StatePanel = Ext.getCmp('tax-serch-detail-panel');
//        	for(var i=0;i<StatePanel.items.keys.length;i++){
//        		var Condition = Ext.getCmp(StatePanel.items.keys[i]);
//        		Condition.hide();
//        	}
        	//增加高级查询中三个条件
//        	var state1 = Ext.getCmp('search-complex-state1').getValue();
//      		state1 = Share.changeCombox(state1);
    		var state2 = Ext.getCmp('express-complex-state2').getValue();
      		state2 = Share.SearchCombox(state2);
    		var state3 = Ext.getCmp('express-complex-state3').getValue();
        	var tabPanel = Ext.getCmp('tab-deal-express');
     		var store = tabPanel.getStore();
     		var SearchPanel = Ext.getCmp('express-complex-search-panel');
     		OldSearch = button.up('window');
     		var paramPanels = SearchPanel.getLayout().getLayoutItems();
     		var str = [];
     		var disstr = [];
        	var fieldNames = [];
        	for(var i=0;i<paramPanels.length;i++){
        		//SearchDetailArray[i] = new Array();  //存放查询数据的二维数组
        		var panelItems = paramPanels[i].getLayout().getLayoutItems();
        		if(panelItems[3].isHidden() == false){
        			if(panelItems[3].getValue() == '' || panelItems[3].getValue() == null){
        				Share.ShowMessage("E0030");
        				return;
        			}
        		}
//        		var basicForm = paramPanels[i].getForm();
        		for(var j = 0;j<panelItems.length;j++){
//        			console.log("TESTPANEL["+j+"]: "+panelItems[j].getValue());
        			if(panelItems[j].isHidden() == true){break;}
        			if(panelItems[j].isHidden() == false && (panelItems[j].getValue() == '' || panelItems[j].getValue() == null)){
        				Share.ShowMessage("E0030");
//        				SearchPanel.hide();
        				return;
        			}
        		}
//        		if (!basicForm.isValid()) {//不可为空
//                    return;
//                }
        		var fieldName = panelItems[0].getValue(); //combobox的valueField
        		var rawName = panelItems[0].getRawValue(); //combobox的displayField
//        		console.log("RAW: "+rawName);
        		var conName = panelItems[1].getRawValue();
        		//SearchDetailArray[i][0] = rawName;  //Array_RawValue
        	//	SearchDetailArray[i][1] = conName;  //Array_condition
        		var orderDir = null;
        		var order2Dir = null;
        		fieldNames.push(fieldName);
        		if(panelItems[1].getValue() == 'between'){  //使用between
        			if(panelItems[0].getValue() == 'document_date' || panelItems[0].getValue() == 'create_date' || panelItems[0].getValue() == 'update_time' || panelItems[0].getValue() == 'INVOICE_DATE' || panelItems[0].getValue() == 'EXPRESS_DATE'){  //使用日期
        				temp = panelItems[3].getRawValue();   //2为text，3为date
        				//SearchDetailArray[i][4] = 3;
        				orderDir = temp;
        			//	SearchDetailArray[i][2] = orderDir;
        				order2Dir = panelItems[6].getRawValue();  //5为text，6为date
        				//SearchDetailArray[i][5] = 6;
        				//SearchDetailArray[i][3] = order2Dir;
        				if(panelItems[0].getValue() == 'update_time'){
							str.push("("+'convert(varchar,UPDATE_TIME ,23)'+conName+' '+"'"+orderDir+"'" + ' and ' + "'" +order2Dir+"'"+")"); 
							}
        				if(panelItems[0].getValue() == 'document_date'){
							str.push("("+'convert(varchar,DOCUMENT_DATE ,23)'+conName+' '+"'"+orderDir+"'" + ' and ' + "'" +order2Dir+"'"+")"); 
							}
        				if(panelItems[0].getValue() == 'INVOICE_DATE'){
							str.push("("+'convert(varchar,INVOICE_DATE ,23)'+conName+' '+"'"+orderDir+"'" + ' and ' + "'" +order2Dir+"'"+")"); 
							}
							if(panelItems[0].getValue() == 'EXPRESS_DATE'){
							str.push("("+'convert(varchar,EXPRESS_DATE ,23)'+conName+' '+"'"+orderDir+"'" + ' and ' + "'" +order2Dir+"'"+")"); 
							}
            				
        				disstr.push("("+rawName+' '+conName+' '+"'"+orderDir+"'" + ' and ' + "'" +order2Dir+"'"+")");
        			}else{//不使用日期
//        				SearchDetailArray[i][1] = 'text';
        				orderDir = panelItems[2].getValue();
        				//SearchDetailArray[i][4] = 2;
        				order2Dir = panelItems[5].getValue();
        			//	SearchDetailArray[i][5] = 5;
        				str.push("("+fieldName+' '+conName+' '+"'"+orderDir+"'" + ' and ' + "'" +order2Dir+"'"+")");
        				disstr.push("("+rawName+' '+conName+' '+"'"+orderDir+"'" + ' and ' + "'" +order2Dir+"'"+")");
        			}
        		}else{ //不使用between
        			if(panelItems[0].getValue() == 'document_date' || panelItems[0].getValue() == 'create_date' || panelItems[0].getValue() == 'update_time' || panelItems[0].getValue() == 'INVOICE_DATE' || panelItems[0].getValue() == 'EXPRESS_DATE'){//使用日期
        				temp = panelItems[3].getRawValue();//2为text，3为date
        			//	SearchDetailArray[i][4] = 3;
        				//SearchDetailArray[i][2] = temp;
        				if(panelItems[1].getValue() == 'like'){
        					temp = "%"+temp+"%";  //如果是like，则使用通配符
        				
        				orderDir = temp;
        				if(panelItems[0].getValue() == 'update_time'){
        								str.push('convert(varchar,UPDATE_TIME ,23)'+' '+'like'+' '+"'"+orderDir+"'");
        							}
        							if(panelItems[0].getValue() == 'document_date'){
        							str.push('convert(varchar,DOCUMENT_DATE ,23)'+' '+'like'+' '+"'"+orderDir+"'");
        							}
        							if(panelItems[0].getValue() == 'INVOICE_DATE'){
        								str.push('convert(varchar,INVOICE_DATE ,23)'+' '+'like'+' '+"'"+orderDir+"'");
        							}
        							if(panelItems[0].getValue() == 'EXPRESS_DATE'){
        							str.push('convert(varchar,EXPRESS_DATE ,23)'+' '+'like'+' '+"'"+orderDir+"'");
        							}	
        				}
        				if(panelItems[1].getValue() == 'in'){  //如果是in
        					orderDir = '';
        					orderTemp = panelItems[3].getRawValue();  //获取第一个textfield值  [2]为date，[3]为text 
        					//SearchDetailArray[i][2] = orderTemp;
        					for(var l=0;l<orderTemp.split(",").length;l++){//如果是in，则为每一个in的条件增加''号
            					orderDir += "'"+orderTemp.split(",")[l]+"'";
            					if(l+1 != orderTemp.split(",").length){orderDir += ',';} 
            				}
            				if(panelItems[0].getValue() == 'update_time'){
        					str.push('convert(varchar,UPDATE_TIME ,23)'+' '+conName+' '+"("+orderDir+")");   //将document_date变为convert(varchar,DOCUMENT_DATE ,23)
        							}
        							if(panelItems[0].getValue() == 'document_date'){
        					str.push('convert(varchar,DOCUMENT_DATE ,23)'+' '+conName+' '+"("+orderDir+")");   //将document_date变为convert(varchar,DOCUMENT_DATE ,23)
        							}
        							if(panelItems[0].getValue() == 'INVOICE_DATE'){
        					str.push('convert(varchar,INVOICE_DATE ,23)'+' '+conName+' '+"("+orderDir+")");   //将document_date变为convert(varchar,DOCUMENT_DATE ,23)
        							}
        							if(panelItems[0].getValue() == 'EXPRESS_DATE'){
        					str.push('convert(varchar,EXPRESS_DATE ,23)'+' '+conName+' '+"("+orderDir+")");   //将document_date变为convert(varchar,DOCUMENT_DATE ,23)
        							}
            				
        					disstr.push(rawName+' '+conName+' '+"("+orderDir+")");
        				}else{  //如果不是in
        						if(panelItems[1].getValue() == '='){
        							orderDir = '';
        							orderDir = panelItems[3].getRawValue();  //获取第一个textfield值  [2]为date，[3]为text 
        					
        					
        							if(panelItems[0].getValue() == 'update_time'){
        								str.push('convert(varchar,UPDATE_TIME ,23)'+' '+'like'+' '+"'"+orderDir+"%'");
        							}
        							if(panelItems[0].getValue() == 'document_date'){
        							str.push('convert(varchar,DOCUMENT_DATE ,23)'+' '+'like'+' '+"'"+orderDir+"%'");
        							}
        							if(panelItems[0].getValue() == 'INVOICE_DATE'){
        								str.push('convert(varchar,INVOICE_DATE ,23)'+' '+'like'+' '+"'"+orderDir+"%'");
        							}
        							if(panelItems[0].getValue() == 'EXPRESS_DATE'){
        							str.push('convert(varchar,EXPRESS_DATE ,23)'+' '+'like'+' '+"'"+orderDir+"%'");
        							}
        							
        						}else if(panelItems[1].getValue() != 'like')
        							
        								{
        						
        							orderDir = '';
        							orderDir = panelItems[3].getRawValue();  //获取第一个textfield值  [2]为date，[3]为text 
        					
        					
        							if(panelItems[0].getValue() == 'update_time'){
        								str.push('convert(varchar,UPDATE_TIME ,23)'+' '+conName+' '+"'"+orderDir+"'");
        							}
        							if(panelItems[0].getValue() == 'document_date'){
        							str.push('convert(varchar,DOCUMENT_DATE ,23)'+' '+conName+' '+"'"+orderDir+"'");
        							}
        							if(panelItems[0].getValue() == 'INVOICE_DATE'){
        								str.push('convert(varchar,INVOICE_DATE ,23)'+' '+conName+' '+"'"+orderDir+"'");
        							}
        							if(panelItems[0].getValue() == 'EXPRESS_DATE'){
        							str.push('convert(varchar,EXPRESS_DATE ,23)'+' '+conName+' '+"'"+orderDir+"'");
        							}	
        						}
//        						
        					
//        					
        					disstr.push(rawName+' '+conName+' '+"'"+orderDir+"'");  //显示值
        				}
        			}else{//不使用日期
        				orderDir = panelItems[2].getValue();  //2为text，3为date
        				//SearchDetailArray[i][2] = orderDir;
        				//SearchDetailArray[i][4] = 2;
        				if(panelItems[1].getValue() == 'in'){
//        					SearchDetailArray[i][1] = 'in';
        					orderDir = '';
        					orderTemp = panelItems[2].getValue();
//        					SearchDetailArray[i][2] = orderTemp;
            				for(var k=0;k<orderTemp.split(",").length;k++){
            					orderDir += "'"+orderTemp.split(",")[k]+"'";
            					if(k+1 != orderTemp.split(",").length){orderDir += ',';} 
            				}
        					str.push(fieldName+' '+conName+' '+"("+orderDir+")");
        					disstr.push(rawName+' '+conName+' '+"("+orderDir+")");
        				}else{
        					if(panelItems[1].getValue() == 'like'){
        						str.push(fieldName+' '+conName+' '+"'%"+orderDir+"%'");
//        						SearchDetailArray[i][1] = conName;
        					}else{
        						str.push(fieldName+' '+conName+' '+"'"+orderDir+"'");
//        						SearchDetailArray[i][1] = conName;
        					}
        					disstr.push(rawName+' '+conName+' '+"'"+orderDir+"'");
        				}
        			}
        		}
//        		i+1 != paramPanels.length ? str.push(fieldName+'='+orderDir+',') : str.push(fieldName+'='+orderDir);//拼写orderby语句，若为最后用一个，无","连接
//        		for(var b=0;b<SearchDetailArray[i].length;b++){
//        			if(SearchDetailArray[i][b] ==null || SearchDetailArray[i][b] == ''){
//        				SearchDetailArray[i][b] = '';
//        			}
//        		}
        	} 
        	var hash = {};        
        	for(var i in fieldNames) {//判断字段名有无重复     
                if(hash[fieldNames[i]]){ 
                	 Share.ShowMessage("I0052");
                     return ;      
                }
                hash[fieldNames[i]] = true;           
            }  
//        	str != '' ? Ext.getCmp('condition-complex-search').setValue(str) : Ext.getCmp('condition-complex-search').hide();
        	//Ext.getCmp('condition-complex-search').show();
        	var Search_Main = new Array();
        	for(var sm=0;sm<Ext.getCmp('express-complex-search-panel').items.items.length;sm++){
    			Search_Main[sm] = Ext.getCmp('express-complex-search-panel').items.items[sm].items.items[0].lastValue;  //高级搜索的选项
    		}
        	Ext.getCmp('search_complex_condition_headforhelp').setValue(Search_Main);
    //    	for(var c=0;c<SearchDetailArray.length;c++){
       // 		for(var x=0;x<SearchDetailArray[c].length;x++){
//        			console.log(SearchDetailArray[c][x]);
        //		}
        //	}
//        	Ext.getCmp('condition-complex-search').setValue(disstr.join(" and ")+'<br/>'+str.join(" and "));   //disstr：显示字符串，str：传递后台字符串
        	//Ext.getCmp('condition-complex-search').setValue(disstr.join("&nbsp;&nbsp;&nbsp;and&nbsp;&nbsp;&nbsp;"));
        	store.currentPage = 1;
        	store.removeAll();
              store.on('beforeload', function(store) {
         			Ext.apply(store.proxy.extraParams , {
         								  str:str.join(" and ")
         								 ,startnum:null
		                                 ,endnum:null
		                                 ,nums:null
		                                 ,startday:null
		                                 ,endday:null
		                                 ,custname:null
		                                 ,goodsname:null
		                                 ,state2:state2
		                                 ,state3:state3});
              });
     		store.load();
     		var win = button.up('window');
        	win.close();
        	OldSearch = win;
    	}if(button.id == 'express-search-button'){
    	 	var startno = Ext.ComponentMgr.get("express-search-sno").getValue() == null ? "":Ext.ComponentMgr.get("express-search-sno").getValue();
      		var endno = Ext.ComponentMgr.get("express-search-eno").getValue()== null ? "":Ext.ComponentMgr.get("express-search-eno").getValue();
      		var nos = Ext.ComponentMgr.get("express-search-nos").getValue().toString()== null ? "":Ext.ComponentMgr.get("express-search-nos").getValue().toString();
      		var sexpressno = Ext.ComponentMgr.get("express-search-sexpressno").getValue()== null ? "":Ext.ComponentMgr.get("express-search-sexpressno").getValue();
      		var eexpressno = Ext.ComponentMgr.get("express-search-eexpressno").getValue()== null ? "":Ext.ComponentMgr.get("express-search-eexpressno").getValue();
      		var startday = Ext.ComponentMgr.get("express-search-sday").getValue()== null ? "":Ext.ComponentMgr.get("express-search-sday").getValue();
      		var endday = Ext.ComponentMgr.get("express-search-eday").getValue()== null ? "":Ext.ComponentMgr.get("express-search-eday").getValue();     
      		var custom = Ext.ComponentMgr.get("express-search-cust").getValue()==null ? "":Ext.ComponentMgr.get("express-search-cust").getValue();
      		var type = null;  
      		var tabpanelId = 'tab-deal-express';
			var tab = Ext.getCmp(tabpanelId);
      		var store = tab.getStore();
      		store.currentPage = 1;
      		store.removeAll();
              store.on('beforeload', function(store) {
         			Ext.apply(store.proxy.extraParams , {startno:(startno==""?null:startno)
         				                                 ,endno:(endno==""?null:endno)
         				                                 ,nos:(nos==""?null:nos)
         				                                 ,sexpressno:(sexpressno==""?null:sexpressno)
         				                                 ,eexpressno:(eexpressno==""?null:eexpressno)
         				                                 ,startday:(startday==""?null:startday)
         				                                 ,endday:(endday==""?null:endday)
         				                                 ,custom:(custom==""?null:custom)
         				                                 ,type:(type==-1?null:type)
         				                                 });
              });
              store.load(); 
              button.up('window').close();
        } if(button.id == 'deal-express-print'){
        	//验证控件是否通过
        	if(!Ext.getCmp("expressStartNo").isValid()){
        		return;
        	}
        	if(!Ext.getCmp("printNum").isValid()){
        		return;
        	}
        	var tabpanelId = 'tab-deal-express';
            var tab = Ext.getCmp(tabpanelId);
            if (tab == undefined) {
                return;
            }
        	//必须至少选择一条记录
            if(tab.getSelectionModel().getCount() == 0) {
            	Share.ShowMessage("I0008");
                return;
            }
        	var row = tab.getSelectionModel().getSelection();
        	
        	for (var s = 0; s < row.length; s++) {
            	if (row[s].get('receiver') == null || row[s].get('receiver') == '') {
            		Share.ShowMessage("I0080");
            		return;
            	}
            }

        	// 取得选中记录的ID
        	var ids = "";
        	for (var i = 0, len = row.length; i < len; i++) {
                var id = row[i].get('id');
                ids += id;
                if (i < len - 1) {
                	ids += "|";
                }
            }
            // 取得打印其他参数
            var express = Ext.getCmp('expressCombobox').value ;
            var expressStartNo = Ext.getCmp('expressStartNo').value;
            var combineRadio = Ext.getCmp('combine');
            var combine = 1;
            combineRadio.items.each(function(item){
        		if(item.checked){
        			combine = item.inputValue;
        		}
        	});
            var printNum = Ext.getCmp('printNum').value;
            var win = Ext.create('Ext.window.Window', {
                title 	  : Share.T('打印方式'),
                width 	  : 280,
                height 	  : 180,
                layout: {
                    type: 'absolute'
                },
                border    : false,
                plain     : true,
                modal 	  : true,
                items     : [ {
					xtype : 'button',
					width : 100,
					height : 50,
					x : 20,
					y : 45,
					text : '下载',
					handler : function(){
						win.close();
						expressprint(0,express,ids,expressStartNo,combine,printNum);
					}
                }, {
					xtype : 'button',
					height : 50,
					x : 150,
					y : 45,
					width : 100,
					text : '直接打印',
					handler : function(){
						win.close();
						expressprint(1,express,ids,expressStartNo,combine,printNum);
					}
                } ]
            }).show();
        }
    },
    save : function(win) {
    	//表单验证通过则继续
        var form = win.down('form');
        var basicForm = form.getForm();
        if (!basicForm.isValid()) {
        	return;
        }
    },

    init: function(application) {
    	this.control({
    		"button": {
                click: this.onButtonClick
            }
    	});
    }
});